import java.io.BufferedInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.OutputStream
import java.util.concurrent.CountDownLatch

class Sender(private val outputStream: OutputStream, private val sb: StringBuilder, private val countDownLatch: CountDownLatch) : Runnable {

    override fun run() {
        try {
            send()
        } catch (e: Exception) {
            printMessage(sb, "发送者（下载）出现异常, ${e.javaClass.simpleName}: ${e.message}")
            e.printStackTrace()
        } finally {
            countDownLatch.countDown()
        }
    }

    private fun send() {
        val file = File(FILE_PATH)
        val fileSize = file.length()
        printMessage(sb, "服务器准备发送视频文件(${formatFileSize(fileSize)})给客户端")
        val dos = DataOutputStream(outputStream)
        dos.writeInt(9981)
        dos.writeLong(fileSize)
        BufferedInputStream(file.inputStream()).use { input ->
            val buf = ByteArray(1024 * 8)
            var length: Int
            var start = System.currentTimeMillis()
            val startTime = start
            var sendPerSecond = 0L
            var sendTotal = 0L
            while (input.read(buf).also { length = it } != -1) {
                outputStream.write(buf, 0, length)
                sendPerSecond += length
                sendTotal += length
                if (System.currentTimeMillis() - start >= 1000L) {
                    printSendSpeed(sendPerSecond, sendTotal, fileSize)
                    start = System.currentTimeMillis()
                    sendPerSecond = 0
                } else if (sendTotal == fileSize) {
                    val second = (System.currentTimeMillis() - start) / 1000f // 把毫秒换成秒
                    sendPerSecond = (sendPerSecond / second).toLong()         // 因为这次的接收的数据还没用到1秒的时间，所以要换算一下
                    printSendSpeed(sendPerSecond, sendTotal, fileSize)
                }
            }
            val totalUseTime = (System.currentTimeMillis() - startTime) / 1000f
            printMessage(sb, "服务器发送视频文件${formatFileSize(fileSize)}完成，总计用时：${totalUseTime}秒，平均${formatFileSize((fileSize / totalUseTime).toLong())}/s")
        }
    }

    private fun printSendSpeed(send: Long, total: Long, fileSize: Long) {
        val sendPerSecond = formatFileSize(send)
        val totalSend = formatFileSize(total)
        val fileLength = formatFileSize(fileSize)
        val percent = total * 100 / fileSize
        printMessage(sb, "↓ $sendPerSecond/s，$totalSend/$fileLength($percent%)")
    }

}